package com.fh.controller;

import com.fh.service.OrdersService;
import com.fh.websocket.WebSocketServer;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("pay")
public class PayController {

    @Resource
    private OrdersService ordersService;

    @RequestMapping("callback")
    public String callback(HttpServletRequest request) throws Exception {
        System.out.println("callback.....");
// 1.接收微信⽀付平台传递的数据（使⽤request的输⼊流接收）
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int length = -1;
        StringBuffer sb = new StringBuffer();
        while ((length = inputStream.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, length));
        }
        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        if (map!=null&&map.get("result_code").equals("SUCCESS")) {


            String orderId = map.get("out_trade_no");
            int i = ordersService.updateOrderStatus(orderId, "2");
            WebSocketServer.sendMsg(orderId, "1");
            if (i > 0) {
                HashMap<String, String> resp = new HashMap<>();
                resp.put("return_code", "success");
                resp.put("return_msg", "OK");
                resp.put("appid", map.get("appid"));
                resp.put("result_code", "success");
                return WXPayUtil.mapToXml(resp);

            }
        }
        return "";
    }


}
